package Utils;

import java.sql.*;

public class DBUtils {
    //1.定义数据库地址，用户名，密码，utf8编码
    public static final String URL = "jdbc:mysql:///carInfo?useSSL=false&useUnicode=true&characterEncoding=utf8";
    public static final String USER = "root";
    public static final String PSW = "root";

    //2.注册驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //3.获取连接对象方法
    public static Connection getConn() {
        Connection conn;
        try {
            conn = DriverManager.getConnection(URL, USER, PSW);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //4.通用的查询方法
    public static ResultSet query(String sql, Object... keys) {
        ResultSet rs;
        try {
            //1.获取连接对象
            Connection conn = getConn();
            //2.获取执行sql语句的对象，并预编译
            PreparedStatement prs = conn.prepareStatement(sql);
            //2.5预编译后，遍历keys数组，将获取的数据赋值给每个?
            for (int i = 0; i < keys.length; i++) {
                prs.setObject((i + 1), keys[i]);
            }
            rs = prs.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //返回结果集
        return rs;
    }

    //5.通用的update方法。（负责增，删，改）
    public static int update(String sql, Object... keys) {

        int num = 0;
        try {
            //1.获取连接对象
            Connection conn = getConn();
            //2.获取执行sql语句的对象，并预编译
            PreparedStatement prs = conn.prepareStatement(sql);
            //2.5预编译后，遍历keys数组，将获取的数据赋值给每个?
            for (int i = 0; i < keys.length; i++) {
                prs.setObject((i + 1), keys[i]);
            }
            num = prs.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //返回一个受影响的函数
        return num;
    }
}
